﻿using PracticeCentre.Modeles;
using PracticeCentre.Mvc.Core.Engines;
using PracticeCentre.Mvc.Core.Logging;
using PracticeCentre.Mvc.Helper;
using System.Web.Mvc;

namespace PracticeCentre.Mvc.Filters
{
    public class WebErrorHandleAttribute : HandleErrorAttribute
    {
        private readonly ILogger _logger;
        public WebErrorHandleAttribute()
        {
            _logger = EngineContainerFactory.GetContainer().GetInstance<ILogger>();
        }
        
        public override void OnException(ExceptionContext filterContext)
        {
            var context = filterContext;
            //记录日志
            //_logger.Error(context.Exception, context.Exception.Message);

            //获取当前的请求对象
            var request = context.RequestContext.HttpContext.Request;
            //如果请求方式为AJax，将返回Json格式数据
            if (request.IsAjaxRequest())
            {
                var result = new JsonResult
                {
                    Data = DataHelper.GetResult(ExecuteState.Failed, "服务器发生异常，请稍候再试或联系管理员",null),
                    ContentEncoding = System.Text.Encoding.UTF8,
                    ContentType = "text/plain"
                };
                context.Result = result;
            }
            else
            {
                context.Result = new RedirectResult("/500"); 
            }
            //设置为已处理
            context.ExceptionHandled = true;
        }
    }
}